package com.kwin.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class CookieApp21 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("网上所有的书籍：" + "<br/>");

        LinkedHashMap<String, Book> bookLinkedHashMap = DB.getAll();
        Set<Map.Entry<String, Book>> entries = bookLinkedHashMap.entrySet();

        for (Map.Entry<String, Book> entry : entries) {
            Book book = entry.getValue();
            resp.getWriter().write("<a href='/CookieApp22?id=" + book.getId() + "&target=_blank'>" + book.getName() + "</a>");
            resp.getWriter().write("<br/>");
        }

        resp.getWriter().write("您曾经浏览过的商品");
        resp.getWriter().write("<br/>");

        Cookie[] cookies = req.getCookies();
        for (int i = 0;cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("bookHistory")) {
                String bookHistory = cookies[i].getValue();
                System.out.println(bookHistory);
                String[] ids = bookHistory.split("\\_");
                for (String id : ids) {
                    Book book = bookLinkedHashMap.get(id);
                    resp.getWriter().write(book.getName());
                    resp.getWriter().write("<br/>");
                }
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
